package com.ihrm.system.controller;

import com.ihrm.common.entity.Result;
import com.ihrm.common.exception.CommonException;
import com.ihrm.domain.system.response.FaceLoginResult;
import com.ihrm.system.service.FaceLoginService;
import com.ihrm.system.utils.BaiduAiUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


@RestController
@RequestMapping("/sys/faceLogin")
public class FaceLoginController {

    @Autowired
    private FaceLoginService faceLoginService;

    @Autowired
    private BaiduAiUtil baiduAiUtil;

    /**
     * 获取刷脸登录二维码
     * 返回值：QRCode对象（code，image）
     */
    @GetMapping("/qrcode")
    public Result qrcode() throws Exception {
        return Result.SUCCESS(faceLoginService.getQRCode());
    }

    /**
     * 检查二维码：登录页面轮询调用此方法，根据唯一标识code判断用户登录情况
     * 查询二维码扫描状态
     * 返回值：FaceLoginResult
     * state ：-1，0，1 （userId和token）
     */
    @GetMapping("/qrcode/{code}")
    public Result qrcodeCeck(@PathVariable String code) throws Exception {
        FaceLoginResult faceLoginResult = faceLoginService.checkQRCode(code);
        return Result.SUCCESS(faceLoginResult);
    }

    /**
     * 人脸登录：根据落地页随机拍摄的面部头像进行登录
     * 根据拍摄的图片调用百度云AI进行检索查找
     */
    @PostMapping("/{code}")
    public Result loginByFace(@PathVariable(name = "code") String code,
                              @RequestParam(name = "file") MultipartFile attachment) throws Exception {
        String userId = faceLoginService.loginByFace(code, attachment);
        if (userId == null) {
            return Result.SUCCESS();
        } else {
            //构造返回数据
            return Result.FAIL();
        }
    }


    /**
     * 图像检测，判断图片中是否存在面部头像
     */
    @PostMapping("/checkFace")
    public Result checkFace(@RequestParam(name = "file") MultipartFile attachment)
            throws Exception {
        if (attachment == null || attachment.isEmpty()) {
            throw new CommonException(10000, "验证失败");
        }
        Boolean aBoolean =
                baiduAiUtil.faceCheck(Base64Utils.encodeToString(attachment.getBytes()));
        if (aBoolean) {
            return Result.SUCCESS();
        } else {
            return Result.FAIL();
        }
    }
}
